﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using HCDV;
using HCDV.HCSP;
using hrainwebbase.basecs;

namespace hrainwebbase.ashx
{
    /// <summary>
    /// PostPhotoHandler 的摘要说明
    /// </summary>
    public class PostPhotoHandler : IHttpHandler
    {
        public enum RequestType
        {
            Auto,
            Form,
            QueryString,
            Cookies
        }
        protected string GetParam(string name, RequestType requestType = RequestType.Auto)
        {
            if ((requestType == RequestType.Auto || requestType == RequestType.Form) && !string.IsNullOrEmpty(Mcontext.Request.Form[name]))
                return Mcontext.Request.Form[name];
            if ((requestType == RequestType.Auto || requestType == RequestType.QueryString) && !string.IsNullOrEmpty(Mcontext.Request.QueryString[name]))
                return Mcontext.Request.QueryString[name];
            if ((requestType == RequestType.Auto || requestType == RequestType.Cookies) && Mcontext.Request.Cookies[name] != null)
                return Mcontext.Request.Cookies[name].Value;
            return "";
        }
        protected HttpContext Mcontext;
        public void ProcessRequest(HttpContext context)
        {
            LogHelper.LogError("postphotoHander");
            Mcontext = context;
            context.Response.ContentType = "application/Json";
            if (context.Request.Files.Count > 0)
            {
                try
                {
                    var random = new Random(Guid.NewGuid().GetHashCode());

                    for (int j = 0; j < context.Request.Files.Count; j++)
                    {
                        LogHelper.LogError("postphotoHander--has" + j.ToString());
                        string savetype = context.Request.QueryString["action"];
                        string imgpostid = GetParam("imgpostid");
                        LogHelper.LogError("postphotoHander--has" + savetype);
                        if (savetype == "dbf")//保存到数据库
                        {
                            HttpPostedFile uploadFile = context.Request.Files[j];

                            if (uploadFile.ContentLength > 0)
                            {
                            
                                byte[] photos = new byte[0];
                                string fullname = DateTime.Now.ToString("yyyyMMddHHmmssffff") + random.Next(10).ToString() + random.Next(10).ToString() + random.Next(10).ToString();
                                string filename = uploadFile.FileName;
                                using (System.IO.Stream MyStream = uploadFile.InputStream)
                                {
                                    photos = new byte[uploadFile.ContentLength];
                                    MyStream.Read(photos, 0, uploadFile.ContentLength);
                                }


                                if (BaseConfig.Dbtype == "mysql")
                                {
                                    using (dbsimple db = new dbsimple())
                                    {
                                        int i = db.hcIsysfileinfo(fullname, photos, filename, imgpostid);
                                    }
                                }
                                else
                                {
                                    using (System.Data.SqlClient.SqlConnection conn = new SqlConnection(HCDV.BaseConfig.ConnectionString))
                                    {
                                        string sql = "INSERT INTO sysfileinfo(fieldid,fieldinfo,fimgname,fpostid)VALUES(@ID,@ImgData) ";
                                        using (SqlCommand cmd = new SqlCommand(sql))
                                        {
                                            SqlParameter param1 = new SqlParameter("ID", SqlDbType.VarChar);
                                            param1.Value = fullname;
                                            cmd.Parameters.Add(param1);

                                            SqlParameter param = new SqlParameter("ImgData", SqlDbType.VarBinary, photos.Length);
                                            param.Value = photos;
                                            cmd.Parameters.Add(param);



                                            SqlParameter param2 = new SqlParameter("fimgname", SqlDbType.VarChar);
                                            param2.Value = filename;
                                            cmd.Parameters.Add(param2);


                                            SqlParameter param3 = new SqlParameter("fpostid", SqlDbType.VarChar);
                                            param3.Value = imgpostid;
                                            cmd.Parameters.Add(imgpostid);

                                            cmd.Connection = conn;
                                            conn.Open();
                                            int i = cmd.ExecuteNonQuery();

                                        }
                                    }

                                }
                                string re = JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(fullname));
                                context.Response.Write(re);// return;
                            }
                        }
                        else
                        {
                            string datetimepath = DateTime.Now.ToString("yyyyMMdd");
                            string uploadPath = context.Server.MapPath("..\\uploads\\" + datetimepath + "\\");
                            string uploadPath_S = context.Server.MapPath("..\\uploads\\s\\" + datetimepath + "\\");
                            HttpPostedFile uploadFile = context.Request.Files[j];

                            if (uploadFile.ContentLength > 0)
                            {
                                //LogHelper.LogError("postphotoHander--yes");
                                string fullname = DateTime.Now.ToString("yyyyMMddHHmmssffff") + random.Next(10).ToString() + random.Next(10).ToString() + random.Next(10).ToString();
                                if (!System.IO.Directory.Exists(uploadPath))
                                {
                                    System.IO.Directory.CreateDirectory(uploadPath);
                                }
                                if (!System.IO.Directory.Exists(uploadPath_S))
                                {
                                    System.IO.Directory.CreateDirectory(uploadPath_S);
                                }
                                // uploadFile.
                                //string extname = Path.GetExtension(uploadFile.FileName);
                                //string fullname = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + (new Random().Next(999).ToString());
                                //string filename = uploadFile.FileName;
                                //uploadFile.FileName
                                //LogHelper.LogError("postphotoHander--yes" + fullname);
                                string imgtype = ".jpg";
                                try
                                {
                                    imgtype = System.IO.Path.GetExtension(uploadFile.FileName);
                                    if (imgtype == null || imgtype == "" || imgtype.IndexOf(".") < 0) imgtype = imgtype + ".jpg";
                                }
                                catch (Exception eee)
                                { imgtype = ".jpg"; }
                                // LogHelper.LogError("postphotoHander--yes" + imgtype);
                                uploadFile.SaveAs(uploadPath + fullname + imgtype);
                                string isimg = "0";
                                //生成缩略图
                                if (".jpg|.gif|.png|.bmp|.jpeg|".IndexOf(imgtype.ToLower()) >= 0)
                                {
                                    isimg = "1";
                                    MakeThumbnail(uploadPath + fullname + imgtype, uploadPath_S + fullname + imgtype, 100, 100);
                                }
                                string re = JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(fullname));
                                using (dbsimple db = new dbsimple())
                                {


                                    db.SpExe(string.Format("insert into sysfileinfo(fieldid,savetype,fsaveurl,fsaveurlmin,fimgname,fpostid,flb3)values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')"
                                        , fullname
                                        , "files"
                                        , "/uploads/" + datetimepath + "/" + fullname + imgtype
                                         , "/uploads/s/" + datetimepath + "/" + fullname + imgtype
                                         , uploadFile.FileName.Replace("%", "")
                                         , imgpostid, isimg
                                        ));
                                }
                                context.Response.Write(re);
                            }
                            else
                            { LogHelper.LogError("postphotoHander--noHttpPostedFile"); }
                        }


                    }
                }
                catch (Exception ex)
                {
                    LogHelper.LogError(ex);
                    string re = JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(ex.Message));
                    context.Response.Write(re);
                }
            }
            else
            {
                LogHelper.LogError("postphotoHander--nono");
                string re = JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("没有收到图片"));
                context.Response.Write(re);
            }
        }
        private void MakeThumbnail(string sourcePath, string newPath, int width, int height)
        {
            System.Drawing.Image ig = System.Drawing.Image.FromFile(sourcePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = ig.Width;
            int oh = ig.Height;
            if ((double)ig.Width / (double)ig.Height > (double)towidth / (double)toheight)
            {
                oh = ig.Height;
                ow = ig.Height * towidth / toheight;
                y = 0;
                x = (ig.Width - ow) / 2;

            }
            else
            {
                ow = ig.Width;
                oh = ig.Width * height / towidth;
                x = 0;
                y = (ig.Height - oh) / 2;
            }
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.Clear(System.Drawing.Color.Transparent);
            g.DrawImage(ig, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            try
            {
                bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ig.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}